import { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { api } from "./api/request";

const LoginPage = () => {
    const [form, setForm] = useState({
        username: '',
        userId: '',
        password: '',
        userType: 'USER' // 假设UserType有USER/ADMIN等值
    });
    const navigate = useNavigate();

    const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setForm(prev => ({ ...prev, [name]: value }));
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        try {
            const res = await api.post('iam/login', form);
            if (res.data.code === 200) {
                // 存储token到localStorage
                localStorage.setItem('token', res.data.data);
                navigate('/blogs/page'); // 登录成功跳转到列表页
            } else {
                alert(res.data.msg);
            }
        } catch (err) {
            console.error('登录失败', err);
        }
    };

    return (
        <div className="login-container">
            <form onSubmit={handleSubmit}>
                <div>
                    <label>用户名</label>
                    <input name="username" value={form.username} onChange={handleChange} required />
                </div>
                <div>
                    <label>用户ID</label>
                    <input name="userId" value={form.userId} onChange={handleChange} required />
                </div>
                <div>
                    <label>密码</label>
                    <input type="password" name="password" value={form.password} onChange={handleChange} required />
                </div>
                <div>
                    <label>用户类型</label>
                    {/*@ts-ignore*/}
                    <select name="userType" value={form.userType} onChange={handleChange}>
                        <option value="USER">普通用户</option>
                        <option value="ADMIN">管理员</option>
                    </select>
                </div>
                <button type="submit">登录</button>
            </form>
        </div>
    );
};

export default LoginPage;